package com.yizisu.playerlibrary.view.video_view.view

import android.app.Activity
import android.content.Context
import android.media.AudioManager
import android.os.Build
import android.provider.Settings
import android.view.*
import com.yizisu.playerlibrary.PlayerLibInit.Companion.app
import com.yizisu.playerlibrary.R
import kotlin.math.abs

/**
 * 调节屏幕亮度（0-1.0）
 * percent：亮度新增比例
 * return 当前亮度
 */
fun View.setScreenBrightnessSlide(offSet: Float/*每次滑动距离百分比，不是总的滑动距离百分比*/): Float {
    (context as? Activity)?.apply {
        return this.setScreenBrightnessSlide(offSet)
    }
    return 0f
}

fun Activity.setScreenBrightnessSlide(offSet: Float): Float {
    val mBrightnessData = getCurrentBrightnessSlide()
    val lpa = window.attributes
    lpa.screenBrightness = mBrightnessData + offSet
    if (lpa.screenBrightness > 1.0f) {
        lpa.screenBrightness = 1.0f
    } else if (lpa.screenBrightness < 0f) {
        lpa.screenBrightness = 0f
    }
    window.attributes = lpa
    return lpa.screenBrightness
}

fun Activity.getCurrentBrightnessSlide(): Float {
    var screenBrightness = window.attributes.screenBrightness
    if (screenBrightness < 0f || screenBrightness > 1f) {
        screenBrightness =
            Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS) / 225f
    }
    return screenBrightness
}


/**
 * return 当前音量百分比
 */
private val audioManager by lazy { app.getSystemService(Context.AUDIO_SERVICE) as AudioManager }

/**
 * 音量调节
 */
fun View.setVolume(offSet: Float/*每次滑动距离百分比，不是总的滑动距离百分比*/): Float {
    val max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
    val saveOffVolume = getTag(R.id.tag_save_current_volume)
    //当前变化的音量
    val offVolume = if (saveOffVolume is Float) {
        saveOffVolume + offSet * max
    } else {
        offSet * max
    }
    val lastVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)

    var newVolume = if (abs(offVolume) > 1f) {
        //变化值已经大于1，可以调节音量
        val split = offVolume.toString().split(".")
        //保存剩余没用消耗值
        setTag(R.id.tag_save_current_volume, "0.${split[1]}".toFloat())
        lastVolume + split[0].toInt()
    } else {
        setTag(R.id.tag_save_current_volume, offVolume)
        lastVolume
    }
    newVolume = when {
        newVolume < 0 -> {
            setTag(R.id.tag_save_current_volume, null)
            0
        }
        newVolume > max -> {
            setTag(R.id.tag_save_current_volume, null)
            max
        }
        else -> {
            newVolume
        }
    }
    if (newVolume != lastVolume) {
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, newVolume, 0)
    }
    return newVolume / max.toFloat()
}

internal fun Window?.fullScreen(isFullScreen: Boolean) {
    val window = this ?: return
    val lp = window.attributes
    if (isFullScreen) {
        // 延伸显示区域到耳朵区
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            lp.layoutInDisplayCutoutMode =
                WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
            window.attributes = lp
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            decorView.windowInsetsController?.apply {
                systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
                hide(WindowInsets.Type.statusBars())
                hide(WindowInsets.Type.navigationBars())
                setDecorFitsSystemWindows(false)
            }
        } else {
            // 允许内容绘制到耳朵区
            val decorView = window.decorView
            window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
            if (decorView.getTag(R.id.tag_save_params_mvvm) == null) {
                decorView.setTag(R.id.tag_save_params_mvvm, decorView.systemUiVisibility)
            }
            decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION)
        }
    } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            lp.layoutInDisplayCutoutMode =
                WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT
            window.attributes = lp
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            decorView.windowInsetsController?.apply {
                show(WindowInsets.Type.statusBars())
                show(WindowInsets.Type.navigationBars())
                setDecorFitsSystemWindows(true)
            }
        } else {
            clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
            val v = decorView.getTag(R.id.tag_save_params_mvvm)
            if (v is Int) {
                decorView.systemUiVisibility = v
            }
        }
    }
}